package edu.csl.study.springboot.config;

import edu.csl.study.springboot.common.ThreadContextHolder;
import org.slf4j.MDC;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskDecorator;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.Map;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 异步任务调度配置
 * 
 * @author Administrator
 *
 */
@Configuration
@EnableAsync
public class AsyncConfig {

	/**
	 * 核心线程条数
	 */
	private final static int CorePoolSize = 10;

	/**
	 * 线程池最大条数
	 */
	private final static int MaxPoolSize = 200;
	/**
	 * 队列大小
	 */
	private final static int QueueCapacity = 10;

	/**
	 * 线程前缀
	 * 
	 * @return
	 */
	private final static String NamePrefix = "AsyncExcutor_";

	@Bean
	public Executor myAsync() {
		ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
		executor.setCorePoolSize(CorePoolSize);
		executor.setMaxPoolSize(MaxPoolSize);
		executor.setQueueCapacity(QueueCapacity);
		executor.setThreadNamePrefix(NamePrefix);
		//异步线程中的MDC和ThreadLocal的使用 ： 如果不设置，默认情况下是不会传递给子线程的。
		executor.setTaskDecorator(new TaskDecorator(){
			@Override
			public Runnable decorate(Runnable runnable) {
				
				Map<String, Object> threadContextMap = ThreadContextHolder.getThreadContextMap();
				Map<String, String> contextMap = MDC.getCopyOfContextMap();
				//函数式编程
				return () ->{
					 try {
						ThreadContextHolder.setThreadContextMap(threadContextMap);
						if (contextMap!=null) {
							MDC.setContextMap(contextMap);
						}
					    runnable.run();
				      } finally {
				    	ThreadContextHolder.remove();
				        MDC.clear();
				      }
				};
			}
			
		});
		// rejection-policy：当pool已经达到max size的时候，如何处理新任务
		// CALLER_RUNS：不在新线程中执行任务，而是有调用者所在的线程来执行
		executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
		executor.initialize();
		return executor;
	}

}
